<!--
 * @Author: JohnYang
 * @Date: 2020-09-23 14:41:53
 * @LastEditors: Zhang Yingying
 * @LastEditTime: 2020-11-23 22:11:28
-->
<template>
  <div class="view">
    <h1>{{ title }}理赔</h1>
    <el-form
      ref="form"
      :rules="rules"
      label-width="120px"
      :model="model"
      v-loading="pending"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="reportTime" label="报案时间：">
            <form-control
              v-model="model.reportTime"
              value-format="yyyy-MM-dd"
              placeholder="请选择报案时间"
              type="date"
              :style="{ width: '100%' }"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="num" label="理赔编号：">
            <form-control
              v-model="model.num"
              type="input"
              placeholder="请填写理赔编号"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="userName" label="客户姓名：">
            <form-control
              v-model="model.userName"
              type="input"
              placeholder="请填写客户姓名"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="telephone" label="客户电话：">
            <form-control
              v-model="model.telephone"
              type="input"
              placeholder="请填写客户电话"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="region" label="质保所在区域：">
            <form-control
              v-model="model.region"
              placeholder="请填写质保所在区域"
              :options="regions"
              type="select"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="dealerName" label="质保提供车行：">
            <form-control
              v-model="model.dealerName"
              placeholder="请填写质保提供车行"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="qualityProduct" label="质保产品：">
            <form-control
              v-model="model.qualityProduct"
              type="select"
              placeholder="请选择质保产品"
              :options="qualityProducts"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="brand" label="品牌：">
            <form-control
              @change="handleBrandChange"
              v-model="model.brand"
              placeholder="请选择品牌"
              :options="brands"
              type="select"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="vehicleModel" label="车型：">
            <form-control
              v-model="model.vehicleModel"
              placeholder="请选择车型"
              :options="CarSubOptions"
              type="select"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="理赔金额：">
            <form-control
              v-model="model.amount"
              placeholder="请输入理赔金额"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="vehicleBug" label="问题：">
            <form-control
              :rows="3"
              v-model="model.vehicleBug"
              placeholder="请填写问题"
              type="textarea"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="process" label="跟进过程：">
            <form-control
              v-model="model.process"
              type="textarea"
              placeholder="请填写跟进过程"
              :rows="3"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="result" label="处理结果：">
            <form-control
              v-model="model.result"
              type="textarea"
              :rows="3"
              placeholder="请填写处理结果"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="维修照片：">
            <file-upload
              @change="handleUploadChange"
              :type="compensateType"
              :file-list="model.repairImgs"
            ></file-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button
              type="danger"
              class="btn-normal"
              @click="handleSubmit"
              :loading="loading"
            >
              保存
            </el-button>
            <el-button type="default" class="btn-normal" @click="handleBack">
              返回
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getCompensate, saveCompensate } from "@/api";
import { validMobilePhone, validRequired, compensateType } from "@/config";
import { RenderMixin } from "@/mixins/render.js";
import { StorageMixin } from "@/mixins/storage";
import FormControl from "@/components/FormControl.vue";
import FileUpload from "@/components/FileUpload.vue";

export default {
  name: "CompensateDetailView",
  mixins: [StorageMixin, RenderMixin],
  components: {
    FormControl,
    FileUpload
  },
  computed: {
    form() {
      return this.$refs.form;
    },
    title() {
      return this.model.id ? "编辑" : "新增";
    }
  },
  mounted() {
    this.setParams();
  },
  data() {
    return {
      compensateType,
      loading: false,
      pending: false,
      temp: "",
      CarSubOptions: [],
      rules: {
        reportTime: [
          validRequired.registerError("请选择报案时间").registerType("string")
        ],
        num: [validRequired.registerError("请填写理赔编号")],
        userName: [validRequired.registerError("请填写客户姓名")],
        telephone: [
          validRequired.registerError("请填写客户电话"),
          validMobilePhone.registerError("客户电话格式不正确")
        ],
        region: [
          validRequired
            .registerError("请填写质保所在区域")
            .registerType("number")
        ],
        dealerName: [validRequired.registerError("请填写质保提供车行")],
        qualityProduct: [
          validRequired.registerError("请选择质保产品").registerType("number")
        ],
        brand: [
          validRequired.registerError("请选择品牌").registerType("number")
        ],
        vehicleModel: [
          validRequired.registerError("请选择车型").registerType("number")
        ],
        vehicleBug: [validRequired.registerError("请填写问题")],
        process: [validRequired.registerError("请填写跟进过程")],
        result: [validRequired.registerError("请填写处理结果")]
      },
      model: {
        id: null,
        reportTime: null,
        num: "",
        userName: "",
        telephone: "",
        region: null,
        dealerName: "",
        qualityProduct: "",
        vehicleModel: "",
        amount: "",
        vehicleBug: "",
        process: "",
        result: "",
        repairImgs: []
      }
    };
  },
  beforeRouteEnter(to, from, next) {
    next();
  },
  beforeRouteLeave(to, from, next) {
    if (this.form) {
      // this.form.resetFields();
      this.resetForm();
      this.form.clearValidate();
    }
    this.$nextTick(() => {
      next();
    });
  },
  methods: {
    resetForm() {
      Object.assign(this.form, {
        id: null,
        reportTime: null,
        num: "",
        userName: "",
        telephone: "",
        region: null,
        dealerName: "",
        qualityProduct: "",
        vehicleModel: "",
        amount: "",
        vehicleBug: "",
        process: "",
        result: "",
        repairImgs: []
      });
    },
    handleUploadChange(data) {
      this.temp = data.join(",");
    },
    setParams() {
      let id = this.$route.query.id;
      this.model.id = id;
      if (!id) {
        return;
      }
      this.getDetailCompensate(id);
    },
    reshapeCompensate(data) {
      return {
        ...data,
        qualityProduct: Number.parseFloat(data.qualityProduct),
        reportTime: this.renderDate(data.reportTime),
        repairImgs: (data.repairImgs || "")
          .split(",")
          .filter(x => x !== "")
          .map((x, idx) => {
            return {
              url: x,
              name: "图片" + idx,
              uid: idx
            };
          })
      };
    },
    async getDetailCompensate(id) {
      try {
        this.pending = true;
        let resp = await getCompensate(id);
        if (resp && resp.data) {
          Object.assign(this.model, this.reshapeCompensate(resp.data));
          this.$nextTick(() => {
            this.handleBrandChange();
            this.model.vehicleModel = resp.data.vehicleModel;
          });
        } else {
          this.$interaction.showError("获取理赔详情失败!");
        }
      } catch (exp) {
        console.error(exp);
      } finally {
        this.pending = false;
      }
    },
    handleBrandChange() {
      this.CarSubOptions = [];
      this.model.vehicleModel = "";
      let brand = this.model.brand;
      this.CarSubOptions = this.getCarsByBrand(brand);
      this.$nextTick(() => {
        this.form && this.form.clearValidate(["vehicleModel"]);
      });
    },
    buildCompensate(data) {
      return { ...data, repairImgs: this.temp };
    },
    handleSubmit() {
      if (this.loading) {
        return;
      }
      this.form &&
        this.form.validate(valid => {
          if (!valid) {
            return;
          }
          this.$interaction.showConfirm({
            message: "确定要保存当前编辑的理赔信息吗?",
            confirmed: async () => {
              try {
                this.loading = true;
                let resp = await saveCompensate(
                  this.buildCompensate(this.model)
                );
                if (resp && resp.code == 0) {
                  this.$interaction.showSuccess("保存成功!");
                  this.doBack();
                } else {
                  this.$interaction.showError("保存失败!");
                }
              } catch (exp) {
                console.error(exp);
              } finally {
                this.temp = "";
                this.loading = false;
              }
            }
          });
        });
    },
    doBack() {
      this.temp = "";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        name: "CompensateStatistics",
        replace: true
      });
    },
    handleBack() {
      this.$interaction.showConfirm({
        message: "确定要放弃编辑，并返回吗?",
        confirmed: this.doBack.bind(this)
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
